$(function(){
	$(document).find("form").each(function(){
		$(this).append('<input name="webform-data-bind" class="webform-data-bind" id="data-bind-value" type="hidden">');
	});
	
	$('.webform-data-bind').val($('#data-bind-serialize').attr('data'));

	$('.result-panel-main').hide();

	$('.reset-signature').on('click', function(){
		var id = $(this).attr('name');
		var canvas = document.getElementById('Field' + id);  
		canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
		$('#Field' + id).sketch('actions',[]);
	});
});

setTimeout(function(){
	var globalErrorMessage = "";
},500);

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

var hostname = window.location.origin;
var hasPhone = false;
var hasLimit = false;
var phoneIdx = "";
var limitIdx = "";

function fieldValidate(fieldId) {
	var isPass = true;	
	globalErrorMessage = "";
	if(fieldId.indexOf('-') > 0) {
		fieldId = fieldId.split('-')[0];
	}

	var field_type = document.getElementById("fieldtype_" + fieldId).value;	
	$('#Field'+fieldId).removeClass('errorBorder');

	if (field_type!="pagebreak" && field_type!="plaintext")
		var required = requireField(fieldId);

	switch (field_type){
		case "text" :
		case "textarea" :
		case "number" :
		case "phone" : 	if(!checkLengthField(fieldId)){isPass = false;}break;
	}

	switch (field_type)
	{	
		case "text" :
		case "textarea" :
		case "redeemcode" : isPass = checkTextField(fieldId, required);
							
		case "hiddentext":
		case "text" :       isPass = checkUniqueText(fieldId, required);
							break;
		case "url" : 		isPass = checkUrlField(fieldId, required);
							break;
		case "radio" :		isPass = checkRadioField(fieldId, required);
							break;
		case "number" :		isPass = checkNumberField(fieldId, required);
							break;						
		case "checkbox" : 	isPass = checkChoiceField(fieldId, required);
							break;
		case "opt"    :  	isPass = checkOptField(fieldId, required);
							break;
		case "birthdate" :
		case "birthmonth" :	
		case "select" :		isPass = checkSelectField(fieldId, required);
							break;
		case "limit" :		isPass = checkSelectField(fieldId, required);
							hasLimit = true;
							limitIdx = limitIdx + "," + fieldId + "-" + document.getElementById("Field" + fieldId).value;
							break;
		case "firstname" :
		case "lastname" :	$('#Field'+fieldId+'-1').removeClass('errorBorder');
							isPass = checkSingleNameField(fieldId, required);
							break;
		case "shortname" : 	isPass = checkNameField(fieldId, required);
							break;
		case "birth":		isPass = checkBirthField(fieldId, required);
							break;
		case "date" : 		isPass = checkDateField(fieldId, required);
							break;
		case "mobilevalidator" : isPass = checkMobileValidator(fieldId, required);
		                    break;
		case "address" : 	isPass = checkAddressField(fieldId, required);
							break;
		case "time" : 		isPass = checkTimeField(fieldId, required);
							break;
		case "email" : 		isPass = checkEmailField(fieldId, required);
							break;
		case "phone" : 		isPass = checkPhoneField(fieldId, required);								
							if (!isEmpty(document.getElementById("Field" + fieldId).value)) {
								hasPhone = true;
								phoneIdx=fieldId;
							}
							break;
		case "membergate" : isPass = checkMemberGateField(fieldId, required);
							break;
		case "likert" : 	isPass = checkLikertField(fieldId, required);
							break;
		case "money" : 		isPass = checkMoneyField(fieldId, required);
							break;
		case "dataquery" :  isPass = checkDataQueryField(fieldId, required);
							break;
		case "datepicker" : isPass = checkDatepicker(fieldId, required);
							break;
		case "sketch" :     isPass = saveSignature(fieldId, required);
		                    break;
		case "password": 	isPass = checkPasswordField(fieldId, required);
							break;    
		case "hkaddressgrp":isPass = checkAddressGroup(fieldId, required);
							break; 
		//case "redeemcode" : isPass = checkRedeemCodeField(fieldId, required);
		//					break;
	}

	if(!isPass) {
		console.log('Question: '+fieldId+' failed in '+field_type+' validation');
	}

	return isPass;
}

function allFieldValidate() {
	var errorCount = 0;
	var isPass = true;
	document.getElementById("errTb").style.display = "none";
	var order_arr = document.getElementsByName("orders");

	for(var indexQ=0; indexQ<order_arr.length; indexQ++){
		var question_no = order_arr[indexQ].value;
		var field_type = document.getElementById("fieldtype_" + question_no).value;

		if(isIE) {
			switch (field_type){
				case "text" :
				case "textarea" :
				case "number" :
				case "phone" :
					if($('#Field'+question_no).attr('placeholder')==$('#Field'+question_no).val()){
						$('#Field'+question_no).val('');
					}
					break;
			}
		}

		if (!fieldValidate(question_no)) {			
			errorCount++;
			if(errorCount == 1) {
				var focusQuestion = '';
				console.log(question_no);
				switch(field_type) {
					case "shortname":
						focusQuestion = question_no+"-1";
						break;
					case "birth":
						focusQuestion = question_no+"-2";
						break;
					default:
						focusQuestion = question_no;
				}

				$("#Field"+focusQuestion).focus();
			}
		}
	}	

	if (errorCount > 0){
		console.log('Error count: ' + errorCount);
		return false;
	} else {
		console.log('Validation Pass!');
		return true;
	}	
}

function clickSave() {
	console.log("click save begin");
	if ($('#submitFormBtn').hasClass('disabledbtn')||$('#submitFormBtn').is(':disabled')) {
		return;
	}
	$('#submitFormBtn').attr('disabled','disabled');
	$('#submitFormBtn').addClass('disabledbtn');
	var isPass = allFieldValidate();
	var theForm = document.getElementById("formPreview");

	if(isPass){
		var order_arr = document.getElementsByName("orders");

		for(var indexQ=0; indexQ<order_arr.length; indexQ++){
			var question_no = order_arr[indexQ].value;

			var hfieldId = $('[name="HiddenFieldID'+question_no+'"]').val();
			if(formRules.length>1){
				$.each(formRules,function(key,eachRuleArr){
					if(typeof(eachRuleArr)!='undefined' && eachRuleArr['ruleData'].field1 == hfieldId){
						if(!checkRule(eachRuleArr)){
							isPass = false;	
						}
					}
				});
			}
			if(isPass && dbRules[hfieldId] != undefined){
				if(!checkDbRule(question_no)){
					isPass = false;
				}
			}

		}
	}
	if(isPass){
		for(var indexQ=0; indexQ<order_arr.length; indexQ++){
			var question_no = order_arr[indexQ].value;
			var field_type = document.getElementById("fieldtype_" + question_no).value;
			if (field_type!="pagebreak" && field_type!="plaintext")
				var required = requireField(question_no);
			switch (field_type)
			{
				case 'redeemcode':
					if(isPass){
						isPass = checkRedeemCodeField(question_no, required);
					}
					break;
			}
		}
	}

	if(formType=='Redemption Form'){
		if(isPass){
			if(typeof confirmRedemption !== 'undefined'&&confirmRedemption==1){
				openFancyboxConfirm();
			}
			else{
				var redeemCodeResult = 0;
				redeemCodeResult = redeemCode();
				if(redeemCodeResult==1){
					document.getElementById("mode").value = "Submit";
					var id = theForm.getAttribute('id');
					replaceSalesforceData();
					theForm = document.getElementById(id);
					theForm.submit();
				}
				else{
					alert('error:'+redeemCodeResult);
				}
			}
		} else {
			console.log("form submit in clickSave function");
			submitForm(theForm, isPass);
		}
	} else if(formType=='Mobile Unsubscribe Form') {
		if(isPass){
			var times=Math.random();
			var url = hostname+'/app/index.php/webforms/form/ajaxCheckMobileUnsubscribe?batchid='+$('#batchid').val()+'&areacode='+$('#AreaCodeField'+phoneIdx).val()+'&mobile='+$('#Field'+phoneIdx).val()+'&times='+times;
			var response = true;
			$.ajax({
			    type: 'GET',
			    url: url ,
			    async:false,
			    success: function(result){
			    	if(result=='OK'){
			    		response = true;
						document.getElementById("mode").value = "Submit";
						theForm.submit();
			    	}
			    	else{
			    		response = false;
			    		isPass = false;
						if(errorMsgArr[phoneIdx]["validErrorMsg"]!=''&&errorMsgArr[phoneIdx]["validErrorMsg"]!='undefined'&&errorMsgArr[phoneIdx]["validErrorMsg"].length > 0){
							document.getElementById("ErrMsg" + phoneIdx).innerHTML = errorMsgArr[phoneIdx]["validErrorMsg"];
							globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[phoneIdx]["validErrorMsg"];
						}
						else{
							document.getElementById("ErrMsg" + phoneIdx).innerHTML = "Please enter valid mobile number";
							globalErrorMessage = globalErrorMessage + "\r\nPlease enter valid mobile number";
						}
						document.getElementById("itemOnPage" + phoneIdx).style.display = "block";
						if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
						    document.getElementById("ErrMsg" + phoneIdx).style.display = "block";

						console.log("form submit in clickSave function");
						submitForm(theForm, isPass);
			    	}
			    },
			});
			console.log('DB check batch mobile-'+' batchid: '+$('#batchid').val()+' areacode: '+$('#AreaCodeField'+phoneIdx).val()+' mobile: '+$('#Field'+phoneIdx).val()+' response: '+response);
		} else {
			console.log("form submit in clickSave function");
			submitForm(theForm, isPass);
		}
		
	} else {
		if(typeof confirmRedemption !== 'undefined'&&confirmRedemption==1 && isPass){
			openFancyboxConfirmNoRedemption(formType);
			return;
		} 
		console.log("form submit in clickSave function");
		submitForm(theForm, isPass);	
	}
}

// scott move from the inlineJS of view page
function clickBack()
{
	document.getElementById("mode").value = "back_submit";
	replaceSalesforceData();
	document.getElementById("formPreview").submit();
}

function clickNext()
{
	document.getElementById("mode").value = "forward_submit";
	replaceSalesforceData();
	document.getElementById("formPreview").submit();
}

function customPreSubmit(){
	return true;
}

function submitForm(theForm, isPass, obj_id){
	var error_msg = "Please correct the error(s) below and try again.";
	if(!customPreSubmit()){
		isPass = false;
	}
	if(isPass==true){
		var id = theForm.getAttribute('id');
		replaceSalesforceData();
		theForm = document.getElementById(id);
		document.getElementById("mode").value = "Submit";
		console.log("form submit in submitForm function");
		theForm.submit();
	}
	else {
		if(errorDisplayWay!='UseRedBoxErrorMessageInWebform'){
			$('[id^="ErrMsg"]').css('display','none');
			globalErrorMessage = globalErrorMessage.substring(2);
			alert(globalErrorMessage);	
		}
		else{
			var errMsg = "";
			errMsg += "                                  <table cellspacing=0 cellpadding=0 border=0 width=\"100%\">\r\n";
			errMsg += "                                    <tr>\r\n";
			errMsg += "                                      <td valign=\"middle\" width=11>\r\n";
			errMsg += "                                        <div class=\"errorleftbox\">&nbsp;</div>\r\n";
			errMsg += "                                      </td>\r\n";
			errMsg += "                                      <td valign=\"middle\" class=\"errormidbox\">\r\n";
			errMsg += "                                        <div style=\"float:left;\">\r\n";
			errMsg += "                                          <div class=\"head_error\">\r\n";
			errMsg += "                                            " + error_msg + "\r\n";
			errMsg += "                                          </div>\r\n";
			errMsg += "                                        </div>\r\n";
			errMsg += "                                      </td>\r\n";
			errMsg += "                                      <td valign=middle width=11>\r\n";
			errMsg += "                                        <div class=\"errorrightbox\">&nbsp;</div>\r\n";
			errMsg += "                                      </td>\r\n";
			errMsg += "                                    </tr>\r\n";
			errMsg += "                                  </table>\r\n";
			document.getElementById("errTb").innerHTML = errMsg;
			document.getElementById("errTb").style.display = "none";
		}
		$("#submitFormBtn").removeAttr('disabled');
		$("#submitFormBtn").removeClass('disabledbtn');
		//location.hash = "#"+err_question; 	
	}
}

//Relace the symbol: space,-,(,)
function strReplacement(val) {
	// var regex = /[-\(\)" ]/g;
	// Match any white space including space, tab, form-feed, etc.
	var re = /\s/g;
	val = val.replace(re, "");
	var re = /\(/g;
	val = val.replace(re, "");
	var re = /\)/g;
	val = val.replace(re, "");
	var re = /\+/g;
	val = val.replace(re, "");
	var re = /\-/g;
	val = val.replace(re, "");
	var re = /\|/g;
	val = val.replace(re, "");
	return val;
}// End the replace function

function requireField(obj_id) {
	var required = false;
	if(($('#req_'+obj_id).length <= 0)){
		
	}
	else if(!isEmpty(document.getElementById("req_" + obj_id).innerHTML)) {
		required = true;
	}
	return required;
}

function checkTextField(obj_id, required) {
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	
	if (isEmpty(this_val) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		console.log($('#Field'+obj_id).attr('class'));
		isPass = false;
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the text field";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkDatepicker(obj_id, required) {
	var isPass = true;
	var id = $(":input[name='HiddenFieldID" + obj_id + "']").val();
	var checked = true;
	
	$('#data_query_error_message_' + id).hide();
	$('#data_query_error_message_' + id).html("");
	$('#ErrMsg' + obj_id).hide();
	$('#ErrMsg' + obj_id).html("");
	var str = $('#Field' + obj_id).val();
	if(str == "" || str == null || isNaN(str)){
		checked = false;
	}
	
	if (required && !checked) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please select a date before submitting form";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the text field";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else {
		if (checked && !checkDatePickerQuota(obj_id)) {
			$('#Field' + obj_id).addClass('errorBorder');
			isPass = false;
			globalErrorMessage = globalErrorMessage
					+ "\r\nThe limit of this date " + obj_id
					+ " is exceeded";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "The limit of this date is exceeded";
			if (errorDisplayWay == 'UseRedBoxErrorMessageInWebform')
				document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
		} else {
			document.getElementById("ErrMsg" + obj_id).style.display = "none";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		}
	}
	return isPass;
}

function checkDataQueryField(obj_id, required) {
	var isPass = true;
	var id = $(":input[name='HiddenFieldID" + obj_id + "']").val();
	var checked = true;
	
	$('#data_query_error_message_' + id).hide();
	$('#data_query_error_message_' + id).html("");
	$('#ErrMsg' + obj_id).hide();
	$('#ErrMsg' + obj_id).html("");
	
	if($('#data_query_button_' + id).attr('data') != null){
		checked = false;
	}
	
	if (required && checked) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please execute data query before submitting form";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the text field";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function updateFieldVal(fieldOrder, value){
	//get field type;
	if($("#fieldtype_" + fieldOrder).length > 0){
		var type = $("#fieldtype_" + fieldOrder).val();
		if(type == 'firstname' || type == 'lastname'){
			$("#Field" + fieldOrder + "-1").val(value);
		}else{
			$("#Field" + fieldOrder).val(value);
		}
	}else{
		$("#Field" + fieldOrder).val(value);
	}
	
}

function checkdataquery(query_id){
	if(typeof dataQuery == undefined){
		return;
	}
	
	if(dataQuery == null){
		return;
	}
	
	if(dataQuery[query_id] == null){
		return;
	}
	
	var processBar = $('#data_query_button_' + query_id).html();	
	if(processBar.indexOf('<img') == 0){
		return;
	}
	
	var tracker = '';
	if (typeof globalTracker!=='undefined'){
		tracker = globalTracker;
	}
	if(getParameterByName('tracker')!=''){
		tracker = getParameterByName('tracker');
	}
	var times=Math.random();
	var id = 'dataquery' + dataQuery[query_id]["mappingid"];
	var source = dataQuery[query_id]["source"];
	var data = {};
	for(var key in source){
		var order = source[key];
		var inputVal = getValueByOrder(order);
		if(inputVal == null){
			inputVal = "";
		}
		data[key] = inputVal;
	}
	var url = hostname+'/app/index.php/webforms/form/ajaxCheckDbRule?id='+id+'&value='+encodeURIComponent(JSON.stringify(data))+'&tracker='+tracker+'&times='+times;
	var button = $('#data_query_button_' + query_id).html();
	var height = 0;
	var ajaxResult = null;
	var orderId = 0;
	$(":input[name='orders']").each(function(){
		if($(":input[name='HiddenFieldID" + $(this).val() + "']").length > 0){
			number = $(this).val();
			order = $(":input[name='HiddenFieldID" + $(this).val() + "']").val();
			if(order == query_id){
				if(errorMsgArr[number]!= null){
					if(errorMsgArr[number]["validErrorMsg"]!= null){
						orderId = number;
					}
				}
			}
		}
	});
	$.ajax({
        type:"GET",
        url:url,
        dataType:"json",
        beforeSend:function(){
        	$('#data_query_button_' + query_id).removeAttr('data');
        	$('#data_query_error_message_' + query_id).html('');
        	$('#data_query_error_message_' + query_id).hide();
        	var panel_id = $('.result-target-' + query_id).attr('id');
        	if(typeof panel_id != undefined && panel_id != null){
        		panel_id = panel_id.replace('table_panel_','');
            	if($('#result_panel_' + panel_id).length > 0){
    				$('#result_panel_' + panel_id).hide();
    			}
        	}
        	$("#ErrMsg" + orderId).html("");
        	$('#submitFormBtn').attr('disabled', 'disabled');
        	$('#submitFormBtn').addClass('disabledbtn');
        	height = $('#submitFormBtn').css('height');
        	$('#data_query_button_' + query_id).html('<img style="height:' + height + '" src="">');
        },
        success:function(data){
        	if(data.result == 'true'){
        		if(data.data.length > 0){
        			ajaxResult = data.data;
            		$('#data_query_result_' + query_id).val(encodeURIComponent(JSON.stringify(data.data)));
        		}
        	}else{
        		console.log('result false');
        	}
        },
        complete: function(XMLHttpRequest, textStatus){
        	$('#submitFormBtn').removeAttr('disabled');
        	$('#submitFormBtn').removeClass('disabledbtn');
        	$('#data_query_button_' + query_id).html(button);
        	var number = 0;
        	var order = 0; 
        	if(ajaxResult == null){
        		$('#data_query_error_message_' + query_id).show();
        		$('#data_query_error_message_' + query_id).html(errorMsgArr[orderId]["validErrorMsg"]);
        	}else if(dataQuery[query_id]['filter'] == 0){
        		if(dataQuery[query_id]["result"] != null){
        			$('#data_query_button_' + query_id).attr('data', JSON.stringify(ajaxResult));
        			for(var key in dataQuery[query_id]["result"]){
        				var result = "";
        				if(ajaxResult.length > 0){
            				result = ajaxResult[0][key];
            				if(result == null){
            					result = "";
            				}
            			}
        				if(dataQuery[query_id]["result"][key] != null){
        					updateFieldVal(dataQuery[query_id]["result"][key], result);
    					}
        			}
        		}
        	}else{
        		if($('.result-target-' + query_id).length > 0){
        			var table_id = $('.result-target-' + query_id).attr('id');
        			id = table_id.replace('table_panel_','');        			
        			var replace_id = 'result_table_' + id;
        			var emptyMessage = 'empty_message_' + id;
        			var emptyFlag = true;
        			if(ajaxResult != null){
        				if (ajaxResult.length > 0) {
    						if (resultPanel[id] != null) {
    							if (resultPanel[id]["title"] != null) {
//    								$('#' + replace_id).find('.result-panel-tr-first-line').each(function(){
//    									html += $(this).prop('outerHTML');
//    								});
    								$('#' + replace_id).find('.result-panel-tr').each(function(){
    									$(this).remove();
    								});
    								$('#data_query_button_' + query_id).attr('data', 'true');
    								//find pattern line;
    								for(var i = 0; i<ajaxResult.length; i++){	
    									//html += $('#result_table_pattern_line_' + query_id).prop('outerHTML');
    									var lineObj = $('#result_table_pattern_line_' + id).clone();
    									var innerH = $('#result_table_pattern_line_' + id).html();
    									innerH = innerH.toString();
    									var patterns = innerH.split('{@@');
    									var keys = Array();
    									for($i = 1; $i < patterns.length; $i++){
    										var breakStr = patterns[$i].split('}');
    										if(breakStr.length >= 2){
    											keys.push(breakStr[0]);
    										}
    									}
    									
    									for(var key in keys){
    										var found = false;
    									    key = keys[key];
    									    key = key.replace("PATTERN_", ""); 
    										replaceWord = '{@@PATTERN_' + key + '}';
											var newValue = '';
    										if (resultPanel[id]["title"][key] != null) {
    											if(typeof ajaxResult[i][key] != undefined && ajaxResult[i][key] != undefined){
    												newValue = ajaxResult[i][key];
    											}
    										}
    										var data = innerH.split(replaceWord);
	    									innerH = data.join(newValue);
    									}
    										
    									lineObj.html(innerH);
    									lineObj.removeAttr('id');
    									lineObj.removeClass('result-panel-pattern');
    									lineObj.addClass('result-panel-tr');
    									lineObj.css('display', 'table-row');
    									$('#' + replace_id).append(lineObj);
    								}
    								emptyFlag = false;
    								if($('#' + replace_id).length > 0){
    									$('#' + replace_id).show();
//    			        				$('#' + replace_id).html(html);
    			        				$('#' + emptyMessage).hide();
    			        			}
    							}
    						}
    					}
        			}
        			
					if(emptyFlag){
						if($('#' + replace_id).length > 0){
	        				$('#' + replace_id).hide();
	        				$('#' + emptyMessage).show();
	        			}
					}
					
        			if($('#result_panel_' + id).length > 0){
        				$('#result_panel_' + id).show();
        			}
        		}else{
        			var pannel = '<table class="data-query-panel"><tr class="data-query-panel-tr">';
        			if(ajaxResult.length > 0){
        				for(var key in ajaxResult[0]){
            				pannel += '<th class="data-query-panel-th">' + key + '</th>';
            			}
            			pannel += '</tr>';
        			
        			  for(var i = 0; i<ajaxResult.length; i++){
        				  pannel += '<tr>';
        				for(var key in ajaxResult[0]){
            				var result = "";
            					result = ajaxResult[i][key];
            					if(result == null){
            						result = "";
            					}
            					pannel += '<td class="data-query-panel-td">' + result + '</td>';
            				}
            				
            		    pannel += '</tr>';
        			  }
        			}
        			pannel += "</table>";
        		    $("#data_query_panel_" + query_id).html(pannel);
        		}
        	}
        		
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        	console.log('fail');
        }
     });
}

function getValueByOrder(order){
	var type = $('#fieldtype_' + order).val();
	var data;
	if(type == 'radio'){
		
	}
	
	if(type == 'checkbox'){
		
	}
	
	data = $('#Field' + order).val();
	
	if(type == 'number'){
		if(!isNumeric(data)){
			return null;
		}
	}
	
	if(typeof data == undefined){
		data = null;
	}
	return data;
}

function isNumeric(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

function checkUniqueText(obj_id, required) {
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	var uniqueCheck = uniqueCheckArr[obj_id];
	textId = $('[name="HiddenFieldID'+obj_id+'"]').val();
	textValue = $('#Field'+obj_id).val();
	
	if(uniqueCheck!=0){
		textValue = $.trim(textValue);
		var uniqueResult = uniqueSubmitCheck(textId,textValue);
		if(!uniqueResult){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			if(errorMsgArr[obj_id]["uniqueErrorMsg"]!=''&&errorMsgArr[obj_id]["uniqueErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["uniqueErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["uniqueErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["uniqueErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "The Value of Question "+obj_id+" is Submitted Before";
				globalErrorMessage = globalErrorMessage + "\r\nThe Value of Question "+obj_id+" is Submitted Before";
			}
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		} else if (uniqueResult == 'err') {
			isPass = false;
		}
	}
	return isPass;
}

function checkUrlField(obj_id, required) {
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	
	var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	
	
	
	if (isEmpty(this_val) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the url";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else {
		if(!isEmpty(this_val) && !RegExp.test(this_val)){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Please validate URL format.";
				globalErrorMessage = globalErrorMessage + "\r\nPlease validate URL format";
			}
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";			
		}else{
			document.getElementById("ErrMsg" + obj_id).style.display = "none";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		}		
	}
	return isPass;
}

function checkNumberField(obj_id, required) {
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	var uniqueCheck = uniqueCheckArr[obj_id];
	var fieldId = $('[name="HiddenFieldID'+obj_id+'"]').val();
	
	if (!checkTextField(obj_id, required)) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
	} else if (!isEmpty(this_val) && !isNum(this_val) && !isFloat(this_val)) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "The value must be numeric format";
			globalErrorMessage = globalErrorMessage + "\r\nThe number field must be numeric format";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if(uniqueCheck!=0){
		var uniqueResult = uniqueSubmitCheck(fieldId,this_val);
		if(!uniqueResult){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			if(errorMsgArr[obj_id]["uniqueErrorMsg"]!=''&&errorMsgArr[obj_id]["uniqueErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["uniqueErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["uniqueErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["uniqueErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "The value is exist. Please check.";
				globalErrorMessage = globalErrorMessage + "\r\nThe value is exist. Please check.";
			}
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		} else if (uniqueResult == 'err') {
			isPass = false;
		}
	}else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkRadioField(obj_id, required) {
	var isPass = true;
	var this_val = "";
	var obj = document.getElementsByName("Field" + obj_id);
	
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			if (this_val != "") {
				this_val += "~##~~##~";
			}
			this_val += obj[i].value;
		}
	}
	if (isEmpty(this_val) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please select the field";
			globalErrorMessage = globalErrorMessage + "\r\nPlease select an option of the radio type question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if($('#otherReq_'+obj_id).length==1) {
		var otherContentName = $('#Field'+obj_id+'_otherContent').attr('name');
		var fieldArr = otherContentName.split('_');
		var choiceId = fieldArr[0].split('--')[1];
		if($('#Field'+obj_id+'-'+choiceId).attr('checked')==true&&$('#Field'+obj_id+'_otherContent').val()==""){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			 
			if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill the other content";
				globalErrorMessage = globalErrorMessage + "\r\nPlease fill the other content";
			}
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
		}
		else {
			document.getElementById("ErrMsg" + obj_id).style.display = "none";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		}
	}else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkChoiceField(obj_id, required) {
	var obj = document.getElementsByName("Choice" + obj_id + '[]');
	var str_val = "";
	var isPass = true;
	
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			if (str_val != "") {
				str_val += "~##~~##~";
			}
			str_val += obj[i].value;
		}
	}
	if (required && str_val == "") {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please select the field";
			globalErrorMessage = globalErrorMessage + "\r\nPlease select an option of the checkbox type question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if($('#otherReq_'+obj_id).length==1) {
		var otherContentName = $('#Field'+obj_id+'_otherContent').attr('name');
		var fieldArr = otherContentName.split('_');
		var choiceId = fieldArr[0].split('--')[1];
		if($('#Field'+obj_id+'-'+choiceId).prop('checked')==true&&$('#Field'+obj_id+'_otherContent').val()==""){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			 
			if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill the other content";
				globalErrorMessage = globalErrorMessage + "\r\nPlease fill the other content";
			}
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
		}
		else {
			document.getElementById("ErrMsg" + obj_id).style.display = "none";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		}
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkOptField(obj_id, required) {
	var obj = document.getElementsByName("Choice" + obj_id + '[]');
	var str_val = "";
	var isPass = true;
	
	for ( var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			if (str_val != "") {
				str_val += "~##~~##~";
			}
			str_val += obj[i].value;
		}
	}
	if (required && str_val == "") {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please select the field";
			globalErrorMessage = globalErrorMessage + "\r\nPlease select an option of the opt type question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if($('#otherReq_'+obj_id).length==1) {
		var otherContentName = $('#Field'+obj_id+'_otherContent').attr('name');
		var fieldArr = otherContentName.split('_');
		var choiceId = fieldArr[0].split('--')[1];
		if($('#Field'+obj_id+'-'+choiceId).prop('checked')==true&&$('#Field'+obj_id+'_otherContent').val()==""){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			 
			if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill the other content";
				globalErrorMessage = globalErrorMessage + "\r\nPlease fill the other content";
			}
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
		}
		else {
			document.getElementById("ErrMsg" + obj_id).style.display = "none";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		}
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}


function checkSelectField(obj_id, required) {
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	var field_type = document.getElementById("fieldtype_" + obj_id).value;
	var minVal = '';
	
	$("#Field"+obj_id+" option").each(function(){
		if(parseInt(this.value)<parseInt(minVal)||minVal==''){
			minVal = this.value;
		}
	});
	if(field_type=='birthdate'||field_type=='birthmonth'){
		minVal = '';
	}
	if (required && this_val == minVal) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please select the field";
			globalErrorMessage = globalErrorMessage + "\r\nPlease select an option of question "+obj_id;
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if(field_type=='limit'){
		if(!uniqueLimitQuota(obj_id)){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			globalErrorMessage = globalErrorMessage + "\r\nThe option limit of Question "+obj_id+" is excceed";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "The option limit of Question "+obj_id+" is excceed";
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
				document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
		}else {
			document.getElementById("ErrMsg" + obj_id).style.display = "none";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		}
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkNameField(obj_id, required) {
	var isPass = true;
	var val1 = document.getElementById("Field" + obj_id + "-1").value;
	var val2 = document.getElementById("Field" + obj_id + "-2").value;
	
	if ((isEmpty(val1) && required) && (isEmpty(val2) && required)) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the name question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
		
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkSingleNameField(obj_id, required) {
	var isPass = true;
	var val1 = document.getElementById("Field" + obj_id + "-1").value;
	
	if (isEmpty(val1) && required) {
		$('#Field'+obj_id + "-1").addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the single name question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else {
		if(!isEmpty(val1) && val1.length < 1) {
			$('#Field'+obj_id + "-1").addClass('errorBorder');
			isPass = false;
			 
			if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Minimal 2 characters needed.";
				globalErrorMessage = globalErrorMessage + "\r\nPlease fill the single name question with minimal 2 characters";
			}
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
		} else {
			document.getElementById("ErrMsg" + obj_id).style.display = "none";
			document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		}
		
	}
	return isPass;
}

function saveSignature(obj_id, required){
	var isPass = true;
	
	if (required) {
		var steps = $('#Field' + obj_id).sketch('actions');
		if(steps.length == 0 || (steps.length == 1 && $.isArray(steps[0]))){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			 
			if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Please select the date";
				globalErrorMessage = globalErrorMessage + "\r\nPlease fill the date question";
			}
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
		}
	}
	
	if (isPass) {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
		
		var obj = {};
		obj.value = document.getElementById("Field" + obj_id).toDataURL();
		obj.width = $("#Field" + obj_id).css('width');
		obj.height = $("#Field" + obj_id).css('height');
		if($('#sketch' + obj_id).length <= 0){
			$('#foli' + obj_id).append('<input id="sketch' + obj_id + '" name="Field' + obj_id +'" type="hidden">');
		}
		$('#sketch' + obj_id).attr('value', JSON.stringify(obj));
	}
	
	return isPass;
}

function checkDateField(obj_id, required) {
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	
	
	if (isEmpty(this_val) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please select the date";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the date question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if (!isEmpty(this_val)) {
		var buffer = this_val.split("/");
		if (buffer.length != 3) {
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
		 
		if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please enter valid date";
			globalErrorMessage = globalErrorMessage + "\r\nPlease enter valid date";
		}
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		}
	}
	if (isPass) {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkAddressField(obj_id, required) {
	var isPass = true;
	var street = document.getElementById("Field" + obj_id + "-1").value;
	var line2 = document.getElementById("Field" + obj_id + "-2").value;
	var city = document.getElementById("Field" + obj_id + "-3").value;
	var region = document.getElementById("Field" + obj_id + "-4").value;
	var zip = document.getElementById("Field" + obj_id + "-5").value;
	var country = document.getElementById("Field" + obj_id + "-6").value;
	
	
	if (isEmpty(street) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the address question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if (!isEmpty(line2) && isEmpty(street)) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please enter valid address";
			globalErrorMessage = globalErrorMessage + "\r\nPlease enter valid address";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkBirthField(obj_id, required) {
	var isPass = true;
	var dd = document.getElementById("Field" + obj_id + "-3").value;
	var mm = document.getElementById("Field" + obj_id + "-2").value;
	
	
	if(document.getElementById("Field" + obj_id + "-1")){
		var yy = document.getElementById("Field" + obj_id + "-1").value;	
	}
	else{
		var yy = '';
		if(dd!=''&&mm!=''){
			yy = '1900';	
		}
	}
	if ((isEmpty(dd) || isEmpty(mm) || isEmpty(yy)) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease enter Birthday question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if ((dd != "" && (mm == "" || yy == ""))
			|| (mm != "" && (dd == "" || yy == ""))
			|| (yy != "" && (dd == "" || mm == ""))) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please valid time";
			globalErrorMessage = globalErrorMessage + "\r\nPlease valid time";
		}
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
	} else {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function confirmMobile(obj_id){
	var isPass = true;
	var id = $('.confirm-mobile').attr('data-target');
	
	$('.confirm-mobile').each(function(){
		if($(this).val() != $('#' + id).val()){
			$('label[data="' + $(this).attr('name') + '"]').text($(this).attr('data-msg')).show();
			$(this).addClass('errorBorder');
			isPass = false;			
		}
		else{
			$(this).removeClass('errorBorder');
			$('label[data="' + $(this).attr('name') + '"]').text($(this).attr('data-msg')).hide();
			isPass = true;		
		}
	});
	
	var validationId = [obj_id];
	
	$('.confirm-areacode').each(function(index){
		if($(this).val() != $('.areacode').val()){
			$(this).addClass('errorBorder');
			$('#C-label' + validationId[0] + '-Confirm').show();
			isPass = false;			
		}
		else{
			$(this).removeClass('errorBorder');
			$('#C-label' + validationId[0] + '-Confirm').hide();
			isPass = true;		
		}
	});
	
	if($('.confirm-mobile').val() == $('#' + id).val()&& $('.confirm-areacode').val() == $('.areacode').val()){
		$('#C-label' + obj_id + '-Confirm').hide();
		$('.field text medium typtxt col-sm-6 col-xs-12 phone confirm-mobile errorBorder').removeClass('errorBorder');
		return isPass;
	}
	else if($('.confirm-mobile').val() == $('#' + id).val()&& $('.confirm-areacode').val() != $('.areacode').val()){
		$('#C-label' + obj_id + '-Confirm').show();
		$('.confirm-areacode').addClass('errorBorder');
	}
}

function checkTimeField(obj_id, required) {
	var isPass = true;
	var hh = document.getElementById("Field" + obj_id + "-1").value;
	var mm = document.getElementById("Field" + obj_id + "-2").value;
	var ss = document.getElementById("Field" + obj_id + "-3").value;
	
	
	if ((isEmpty(hh) || isEmpty(mm) || isEmpty(ss)) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill in the time question";
		}
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} else if ((hh != "" && (mm == "" || ss == ""))
			|| (mm != "" && (hh == "" || ss == ""))
			|| (ss != "" && (hh == "" || mm == ""))) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please valid time";
			console.log('checkemail-obj_id: '+obj_id);
			globalErrorMessage = globalErrorMessage + "\r\nPlease valid time";
		}
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
	} else {
		/*
		 * document.getElementById("Field" + i + "-5").value = hh + ":" + "mm" +
		 * ":" + "ss" + document.getElementById("Field" + i + "-4").value;
		 */
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}



function checkMemberGateField(obj_id, required) {
	var isPass = true;
	var this_val = '';
	var minVal = '';
	
	var contactMatch = memberGateMatchArr[obj_id]["contactAttribute"];
	var compareType = memberGateMatchArr[obj_id]["compareType"];
	
	this_val = document.getElementById("Field" + obj_id).value;
	var this_val = document.getElementById("Field" + obj_id).value;
	var fieldId = $('[name="HiddenFieldID'+obj_id+'"]').val();
	var uniqueCheck = uniqueCheckArr[obj_id];
	if (isEmpty(this_val) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your "+contactMatch;
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill in your "+contactMatch;
		}
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
	} else if (!isEmpty(this_val)) {
		this_val = strReplacement(this_val);
		if (this_val.length<8) {
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Please enter valid "+contactMatch;
				globalErrorMessage = globalErrorMessage + "\r\nPlease enter valid "+contactMatch;
			}
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		}
		var contactExistCheck = contactMatchCheck(contactMatch,compareType,this_val);
		if(contactExistCheck<=0){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			if(errorMsgArr[obj_id]["attributeCompareErrorMsg"]!=''&&errorMsgArr[obj_id]["attributeCompareErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["attributeCompareErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["attributeCompareErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["attributeCompareErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Sorry, the data entered could not be found in our member's database";
				globalErrorMessage = globalErrorMessage + "\r\nSorry, the data entered could not be found in our member's database";
			}
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		}
		else{
			$('#memberGateContactId_'+obj_id).val(contactExistCheck);
		}
		if(uniqueCheck!=0){
			var uniqueResult = uniqueSubmitCheck(fieldId,this_val);
			if(!uniqueResult){
				$('#Field'+obj_id).addClass('errorBorder');
				isPass = false;
				if(errorMsgArr[obj_id]["uniqueErrorMsg"]!=''&&errorMsgArr[obj_id]["uniqueErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["uniqueErrorMsg"].length > 0){
					document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["uniqueErrorMsg"];
					globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["uniqueErrorMsg"];
				}
				else{
					document.getElementById("ErrMsg" + obj_id).innerHTML = "One "+contactMatch+" can only submit once";
					globalErrorMessage = globalErrorMessage + "\r\nOne "+contactMatch+" can only submit once";
				}
				document.getElementById("itemOnPage" + obj_id).style.display = "block";
				if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
				    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			} else if (uniqueResult == 'err') {
				isPass = false;
			}
		}
	} 
	if (isPass) {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkDbRule(obj_id){
	var tracker = '';
	if (typeof globalTracker!=='undefined'){
		tracker = globalTracker;
	}
	if(getParameterByName('tracker')!=''){
		tracker = getParameterByName('tracker');
	}

	var fieldId = $('[name="HiddenFieldID'+obj_id+'"]').val();
	var fieldType = document.getElementById("fieldtype_" + obj_id).value;
	var fieldvalue = $('#Field'+obj_id).val();
	if(fieldType == 'phone' && fieldvalue != ''){
		var areaCode = '';
		if($("#AreaCodeField" + obj_id).length>0){
			areaCode = $("#AreaCodeField" + obj_id + " option:selected").val();
		}
		fieldvalue = strReplacement(areaCode + fieldvalue);
	}

	if(fieldvalue!=''){
	  var response = true;
      $.each(dbRules[fieldId],function(dbrkey,eachRuleArr){
       if(typeof(eachRuleArr)!='undefined' && response == true){
		var times=Math.random();
		var url = hostname+'/app/index.php/webforms/form/ajaxCheckDbRule?id='+dbrkey+'&value='+fieldvalue+'&tracker='+tracker+'&times='+times;
		if($("#salesforce_replace_area_" + dbrkey).length > 0){
			$("#salesforce_replace_area_" + dbrkey).remove();
		}
		$.ajax({
		    type: 'GET',
		    url: url ,
		    async:false,
		    success: function(result){
				if (result == 'OK') {
					response = true;
				} else {
					if (result.length > 2) {
						if (result.substr(0, 1) == "{") {
							var obj = JSON.parse(result);
							var jdata = obj.data;
							var appendHtml = "<div id='salesforce_replace_area_" + dbrkey + "'>";
							var count = 1;
							for ( var key in obj.data) {
								appendHtml += "<input id='salesforce_replace_" + count + "' type='hidden' class='salesforce-replace-data'>"
								count++;
							}
							appendHtml += "</div>";
							$("body").append(appendHtml);
							var count = 1;
							for ( var key in obj.data) {
								var keyword = '##~' + key + '~##';
								$("#salesforce_replace_" + count).attr("name", keyword);
								$("#salesforce_replace_" + count).val(jdata[key]);
								count++;						
							}
							response = true;
						} else {
							response = false;
							document.getElementById("ErrMsg" + obj_id).innerHTML = eachRuleArr['errorMsg'];
							if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
							    document.getElementById("ErrMsg" + obj_id).style.display = "block";
						}
					} else {
						response = false;
						document.getElementById("ErrMsg" + obj_id).innerHTML = eachRuleArr['errorMsg'];
						if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
						    document.getElementById("ErrMsg" + obj_id).style.display = "block";
					}
				}
		    },
		});
		console.log('DB check rules'+dbrkey+' values: '+fieldvalue+' response: '+response);
       }
	  });
		return response;
	} else {
		console.log('DB check rules with empty value');
		return true;
	}

}

function replaceSalesforceData(){
	$('.salesforce-replace-data').each(function(){
		var replaced = $("body").html().replace(
				new RegExp($(this).attr('name'), "igm"), $(this).val());
		$("body").html(replaced);
	});
}

function checkRedeemCodeField(obj_id, required) {
	var isPass = true;
	var this_val = '';
	var minVal = '';
	
	this_val = document.getElementById("Field" + obj_id).value;
	var this_val = document.getElementById("Field" + obj_id).value;
	var fieldId = $('[name="HiddenFieldID'+obj_id+'"]').val();
	var uniqueCheck = uniqueCheckArr[obj_id];
	if (isEmpty(this_val) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your Redeem Code";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill in your Redeem Code";
		}
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
	} else if (!isEmpty(this_val)) {
		this_val = strReplacement(this_val);
		var issueCodeResult = issueCode(this_val, fieldId);
		if(issueCodeResult!=0){
			$('#Field'+obj_id).addClass('errorBorder');
			isPass = false;
			if(errorMsgArr[obj_id]["attributeCompareErrorMsg"]!=''&&errorMsgArr[obj_id]["attributeCompareErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["attributeCompareErrorMsg"].length > 0){
				document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["attributeCompareErrorMsg"];
				globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["attributeCompareErrorMsg"];
			}
			else{
				document.getElementById("ErrMsg" + obj_id).innerHTML = "Sorry, the data entered could not be found in our member's database";
				globalErrorMessage = globalErrorMessage + "\r\nSorry, the data entered could not be found in our member's database";
			}
			document.getElementById("itemOnPage" + obj_id).style.display = "block";
			if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
			    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		}
		if(uniqueCheck!=0){
			var uniqueResult = uniqueSubmitCheck(fieldId,this_val);
			if(!uniqueResult){
				$('#Field'+obj_id).addClass('errorBorder');
				isPass = false;
				if(errorMsgArr[obj_id]["uniqueErrorMsg"]!=''&&errorMsgArr[obj_id]["uniqueErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["uniqueErrorMsg"].length > 0){
					document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["uniqueErrorMsg"];
					globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["uniqueErrorMsg"];
				}
				else{
					document.getElementById("ErrMsg" + obj_id).innerHTML = "One Redeem code can only submit once";
					globalErrorMessage = globalErrorMessage + "\r\nOne Redeem code can only submit once";
				}
				document.getElementById("itemOnPage" + obj_id).style.display = "block";
				if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
				    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			} else if (uniqueResult == 'err') {
				isPass = false;
			}
		}
	} 
	if (isPass) {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkLikertField(obj_id, required) {
	var isPass = true;
	var selected = false;
	var buffer = (document.getElementById("hidlikert" + obj_id).value)
			.split(",");
	
	for(var i = 0; i< buffer.length; i++){
		if(buffer[i].length<=0 || buffer[i] == null || buffer[i] == "")
		{
			
		}
		else{
			var selected = false;
			var likerId = "likert_" + buffer[i];
			var chkObjs = document.getElementsByName(buffer[i] + "_radio");
			var fieldid=$("input[name='HiddenFieldID"+obj_id+"']").val();
			var error_obj_id = buffer[i];
			for(var j=0;j<chkObjs.length;j++){
				if(chkObjs[j].checked){
					document.getElementById(likerId).value = fieldid + ":" + buffer[i] + ":" + chkObjs[j].id;
					selected = true;
					break;
				}else{
				}
			}
			if(!selected)
			{
				document.getElementById(likerId).value  = fieldid + ":" + buffer[i] + ":" +  "0";
			}
		}
	}
	
	if (required) {
		var likert_id = "Field" + obj_id;
		for(var i = 0; i< buffer.length; i++){
			if(buffer[i].length<=0 || buffer[i] == null || buffer[i] == "")
			{
				
			}else{
				var selected = false;
				var chkObjs = document.getElementsByName(buffer[i] + "_radio");
				var error_obj_id = buffer[i];
				for(var j=0;j<chkObjs.length;j++){
					if(chkObjs[j].checked){
						chk = j+1;
						selected = true;
						break;
					}else{
					}
				}
				error_obj_id = "ErrMsg" + error_obj_id;
				if (!selected) {
					$('#Field'+obj_id).addClass('errorBorder');
					isPass = false;
					isChecked = false;
					document.getElementById(error_obj_id).style.color = "red";
					if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
						document.getElementById(error_obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
						globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
					}
					else{
						document.getElementById(error_obj_id).innerHTML = "Please select the value";
						globalErrorMessage = globalErrorMessage + "\r\nPlease fill the likert question";
					}
					document.getElementById("itemOnPage" + obj_id).style.display = "block";
					if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
						document.getElementById(error_obj_id).style.display = "block";
					break;
				}else{
					document.getElementById(error_obj_id).style.display = "none";
					document.getElementById(error_obj_id).innerHTML = "";
				}
			}
		}
	}
	if (isPass) {
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkMoneyField(obj_id, required) {
	var isPass = true;
	var dollars = document.getElementById("Field" + obj_id + "-1").value;
	var cents = document.getElementById("Field" + obj_id + "-2").value;
	
	
	if ((isEmpty(dollars) || isEmpty(cents)) && required) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["emptyErrorMsg"]!=''&&errorMsgArr[obj_id]["emptyErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["emptyErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["emptyErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["emptyErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please fill in your information";
			globalErrorMessage = globalErrorMessage + "\r\nPlease fill the money field";
		}
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
	} else if ((!isEmpty(dollars) && !isNum(dollars))
			|| (!isEmpty(cents) && !isNum(cents))) {
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		 
		if(errorMsgArr[obj_id]["validErrorMsg"]!=''&&errorMsgArr[obj_id]["validErrorMsg"]!='undefined'&&errorMsgArr[obj_id]["validErrorMsg"].length > 0){
			document.getElementById("ErrMsg" + obj_id).innerHTML = errorMsgArr[obj_id]["validErrorMsg"];
			globalErrorMessage = globalErrorMessage + "\r\n"+errorMsgArr[obj_id]["validErrorMsg"];
		}
		else{
			document.getElementById("ErrMsg" + obj_id).innerHTML = "Please enter valid price";
			globalErrorMessage = globalErrorMessage + "\r\nPlease enter valid price";
		}
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
	} else {
		if (!isEmpty(dollars) || !isEmpty(cents)) {
			if (isEmpty(dollars)) {
				document.getElementById("Field" + obj_id + "-1").value = 0;
			}
			if (isEmpty(cents)) {
				document.getElementById("Field" + obj_id + "-2").value = 0;
			}
		}
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function checkOfficialRule() {
	var isPass = true;
//	if (document.getElementById("useofficialrule").value == 1) {
//		if (document.getElementById("mandatoryofficialrule").value == 1) {
//			if (document.getElementById("acceptofficialrule").checked) {
//				document.getElementById("ErrOfficialRule").style.display = "none";
//			} else {
//				$('#Field'+obj_id).addClass('errorBorder');
//				isPass = false;
//				document.getElementById("ErrOfficialRule").innerHTML = "You must tick the check box before submission can be accepted";
//				document.getElementById("ErrOfficialRule").style.display = "block";
//			}
//		}
//	}
	return isPass;
}

function checkPasswordField(obj_id, required) {
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	
	if (required && isEmpty(this_val) || required && (this_val).length < 6 || !required && (this_val).length < 6 && !isEmpty(this_val)) {
		$('#Field'+obj_id).addClass('errorBorder');
		console.log($('#Field'+obj_id).attr('class'));
		isPass = false;
		document.getElementById("ErrMsg" + obj_id).innerHTML = "Password must be at least 6 characters long";
		globalErrorMessage = globalErrorMessage + "\r\nPlease fill the text field";
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
		document.getElementById("itemOnPage" + obj_id).style.display = "block";
	} 
	else if(!required && isEmpty(this_val)){
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
		document.getElementById("ErrMsg" + obj_id).innerHTML = "";
	}
	return isPass;
}

function lengthField(obj_id){
	var len = document.getElementById("length_" + obj_id).value;
	if(!isEmpty(len)){
		return len;
	}
	return false
}

function checkLengthField(obj_id){
	var isPass = true;
	var this_val = document.getElementById("Field" + obj_id).value;
	var len = lengthField(obj_id);
	if( len!==false  &&  (len|0)>0  &&  this_val.replace(/^\s+|\s+$/g, "").length>len){
		$('#Field'+obj_id).addClass('errorBorder');
		isPass = false;
		document.getElementById("ErrMsg" + obj_id).innerHTML = "The max length of the value : "+ (len|0);
		if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
		    document.getElementById("ErrMsg" + obj_id).style.display = "block";
	}else{
		document.getElementById("ErrMsg" + obj_id).style.display = "none";
	}
	return isPass;
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function uniqueSubmitCheck(id,value){
	var tracker = '';
	console.log("type of group id["+id+"]: "+typeof group_id);
	if (typeof group_id!='undefined') {
				id = group_id[id];
		console.log("group id used: "+group_id[id]);
	}
	if (typeof globalTracker!=='undefined'){
		tracker = globalTracker;
	}
	if(getParameterByName('tracker')!=''){
		tracker = getParameterByName('tracker');
	}

	var url = hostname+'/app/index.php/webforms/form/ajaxCheckRepeat?id='+id+'&value='+encodeURIComponent(value)+'&tracker='+tracker;
	if(typeof summary_report_id !== 'undefined'){
		url += '&rid=' + summary_report_id;
	}
	var response = true;
	$.ajax({ 
	    type: 'GET',
	    url: url ,
	    async:false,
	    success: function(result){
	    	if(result=='Existed'){
	    		response = false;
	    	}
	    	else{
	    		response = true;
	    	}
	    },
	    error: function(){
	    	response = 'err';
	    	var theForm = document.getElementById("formPreview");
	    	var isPass = false;
	    	$('#sysErrMsg').html('Sorry unable to submit, please check your Internet Connection and try again.');
			$.fancybox.open([ {
				href : '#sysErr',
				parent: "form:first"
			} ], {
				padding : 20
			});
	    	submitForm(theForm, isPass);
	    },
	});
	return response;
}
function contactMatchCheck(attributeName,compareType,value){
	var tracker = '';
	if (typeof globalTracker!=='undefined'){
		tracker = globalTracker;
	}
	if(getParameterByName('tracker')!=''){
		tracker = getParameterByName('tracker');
	}
	var url = hostname+'/app/index.php/webforms/form/ajaxCheckContactExist?attributeName='+attributeName+'&compareType='+compareType+'&value='+encodeURIComponent(value)+'&tracker='+tracker;
	var response = true;
	$.ajax({ 
	    type: 'GET',
	    url: url ,
	    async:false,
	    success: function(result){
	    	if(result>0){
	    		response = result;
	    	}
	    	else{
	    		response = -1;
	    	}
	    },
	});
	return response;
}
function issueCode(value, fieldid){
	var tracker = '';
	if (typeof globalTracker!=='undefined'){
		tracker = globalTracker;
	}
	if(getParameterByName('tracker')!=''){
		tracker = getParameterByName('tracker');
	}
	
	var url = hostname+'/app/index.php/webforms/form/ajaxissueCode?identifier='+fieldid+'&value='+value+'&fieldid=true&tracker='+tracker;
	if(!$.isNumeric( fieldid )){
		url = hostname+'/app/index.php/webforms/form/ajaxissueCode?identifier='+identifier+'&value='+value+'&tracker='+tracker;
	}
	var response = -1;
	$.ajax({ 
	    type: 'GET',
	    url: url ,
	    async:false,
	    success: function(result){
	    	if(result==0){
	    		response = result;
	    	}
	    },
	});
	return response;
}

function checkDatePickerQuota(quesNo){
	var choiceId = $( "#Field"+quesNo).val();
	var tracker = '';
	if (typeof globalTracker!=='undefined'){
		tracker = globalTracker;
	}
	if(getParameterByName('tracker')!=''){
		tracker = getParameterByName('tracker');
	}
	
	if(tracker==''){
//		tracker = '415d70fa-644e-4977-1fd9-ec45c899ebbc';
//		tracker = 'd8086492-adcb-11e3-b29c-7aaf34084b51';
	}
	var times=Math.random();
	var url = hostname+'/app/index.php/webforms/form/ajaxCheckLimitQuota?id='+choiceId+'&tracker='+tracker+'&times='+times;
	if(typeof summary_report_id !== 'undefined'){
		url += '&rid=' + summary_report_id;
	}
	
	var response = false;
	$.ajax({
	    type: 'GET',
	    url: url ,
	    async:false,
	    success: function(result){
	    	if(result=='Exceed'){
	    		response = false;
	    	}
	    	else{
	    		response = true;
	    	}
	    },
	});
	return response;
}

function uniqueLimitQuota(quesNo){
	var choiceId = $( "#Field"+quesNo+" option:selected" ).val();
	var tracker = '';
	if (typeof globalTracker!=='undefined'){
		tracker = globalTracker;
	}
	if(getParameterByName('tracker')!=''){
		tracker = getParameterByName('tracker');
	}
	
	if(tracker==''){
//		tracker = '415d70fa-644e-4977-1fd9-ec45c899ebbc';
//		tracker = 'd8086492-adcb-11e3-b29c-7aaf34084b51';
	}
	var times=Math.random();
	var qty = 1;
	if($('#quotaqty_'+quesNo).length >0 && isNumeric($('#quotaqty_'+quesNo).val())){
		qty = $('#quotaqty_'+quesNo).val();
	}
	var url = hostname+'/app/index.php/webforms/form/ajaxCheckLimitQuota?id='+choiceId+'&qty='+qty+'&tracker='+tracker+'&times='+times;
	if(typeof summary_report_id !== 'undefined'){
		url += '&rid=' + summary_report_id;
	}
	var response = false;
	$.ajax({
	    type: 'GET',
	    url: url ,
	    async:false,
	    success: function(result){
	    	if(result=='OK'){
	    		response = true;
	    	}
	    	else{
	    		response = false;
	    	}
	    },
	    error: function(){
	    	response = false;
	    },
	});
	return response;
}

function checkRule(ruleArr){
	var fieldAId = ruleArr['ruleData'].field1;
	var fieldBId = ruleArr['ruleData'].field2;
	fieldAIdArr = new Array();
	fieldBIdArr = new Array();
	if (fieldAId.indexOf('&&')>=0) {
		fieldAIdArr = fieldAId.split('&&');
		fieldAId = fieldAIdArr[0];
		console.log("Split field A Id: "+fieldAId);
	}
	if (fieldBId.indexOf('&&')>=0) {
		fieldBIdArr = fieldBId.split('&&');
		fieldBId = fieldBIdArr[0];
		console.log("Split field B Id: "+fieldBId);
	}	
	var fieldAOrder = parseInt(getOrderById(fieldAId));
	var fieldBOrder = parseInt(getOrderById(fieldBId));
	var rule = ruleArr['ruleData'].rule;
	var isPass = true;
	if(fieldAOrder!=''&&fieldBOrder!=''){
		if($('#fieldtype_'+fieldAOrder).val()=='firstname' || $('#fieldtype_'+fieldAOrder).val()=='lastname'){
			var fieldA = $('#Field'+fieldAOrder+'-1').val();
		} else {
			var fieldA = $('#Field'+fieldAOrder).val();
			console.log("Field A length: "+fieldAIdArr.length);
			if (fieldAIdArr.length>1) {
				fieldAOrder1 = parseInt(getOrderById(fieldAIdArr[1]));
				if ($('#fieldtype_'+fieldAOrder).val()=='select') {
					fieldA0 =$('#Field'+fieldAOrder+" option:selected").text();
				} else {
					fieldA0 = $('#Field'+fieldAOrder).val();
				}
				if ($('#fieldtype_'+fieldAOrder1).val()=='select') {
					fieldA1 =$('#Field'+fieldAOrder1+" option:selected").text();
				} else {
					fieldA1 = $('#Field'+fieldAOrder1).val();
				}
				
				fieldA = fieldA0+fieldA1;
				console.log("concat field A ("+fieldAIdArr[0]+" + "+fieldAIdArr[1]+"): "+fieldA);
			} else if (fieldA == ''||fieldAIdArr.length==0){
				fieldA = $('#Field'+fieldAOrder).val();
				console.log("FieldA value: "+fieldA);
				if ($('#fieldtype_'+fieldAOrder).val()=='radio'||$('#fieldtype_'+fieldAOrder).val()=='checkbox') {
					fieldA = $('input[name="Field'+fieldAOrder + '"]:checked' ).next('label:first').html();
					console.log("FieldA checked value: "+fieldA);
				}
				
			}
		}
		
		var fieldB = $('#Field'+fieldBOrder).val();
		if (fieldBIdArr.length>1) {
			fieldBOrder1 = parseInt(getOrderById(fieldBIdArr[1]));
			if ($('#fieldtype_'+fieldBOrder).val()=='select') {
				fieldB0 =$('#Field'+fieldBOrder+" option:selected").text();
			} else {
				fieldB0 = $('#Field'+fieldBOrder).val();
			}
			if ($('#fieldtype_'+fieldBOrder1).val()=='select') {
				fieldB1 =$('#Field'+fieldBOrder1+" option:selected").text();
			} else {
				fieldB1 = $('#Field'+fieldBOrder1).val();
			}
			
			fieldB = fieldB0+fieldB1;
			console.log("concat field B ("+fieldBIdArr[0]+" + "+fieldBIdArr[1]+"): "+fieldB);
		}
		var fieldAType = $('#fieldtype_'+fieldAOrder).val();
		var fieldBType = $('#fieldtype_'+fieldBOrder).val();
		if (fieldAType=='phone'&&fieldA!='') {
			if ($('#AreaCodeField'+fieldAOrder).length > 0) {
				fieldA = $('#AreaCodeField'+fieldAOrder+" option:selected").val()+fieldA;
				console.log("concat areacode with phone A value: "+fieldA);
			}
		}
		
		if (fieldBType=='phone'&&fieldB!='') {
			if ($('#AreaCodeField'+fieldBOrder).length > 0) {
				fieldB = $('#AreaCodeField'+fieldBOrder+" option:selected").val()+fieldB;
				console.log("concat areacode with phone B value: "+fieldB);
			}
		}
		
		if(rule=='notequal'){
			console.log("not equal compare >>> fieldA: "+fieldA+" and fieldB: "+fieldB);
			if(fieldA!=''&&fieldA==fieldB){
				obj_id = fieldAOrder;
				$('#Field'+obj_id).addClass('errorBorder');
				isPass = false;
				console.log(ruleArr);
				if(ruleArr['errorMsg']!=''&&ruleArr['errorMsg']!='undefined'&&ruleArr['errorMsg'].length > 0){
					document.getElementById("ErrMsg" + obj_id).innerHTML = ruleArr['errorMsg'];
					globalErrorMessage = globalErrorMessage + "\r\n"+ruleArr['errorMsg'];
				}
				else{
					document.getElementById("ErrMsg" + obj_id).innerHTML = "answer can not be same";
					globalErrorMessage = globalErrorMessage + "\r\nanswer can not be same";
				}
				document.getElementById("itemOnPage" + obj_id).style.display = "block";
				if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
				    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			}
		}
		if(rule=='equal'){
			console.log("equal compare >>> fieldA: "+fieldA+" and fieldB: "+fieldB);
			if(fieldA!=''&&fieldA!=fieldB){
				obj_id = fieldAOrder;
				$('#Field'+obj_id).addClass('errorBorder');
				isPass = false;
				console.log(ruleArr['errorMsg']);
				if(ruleArr['errorMsg']!=''&&ruleArr['errorMsg']!='undefined'&&ruleArr['errorMsg'].length > 0){
					document.getElementById("ErrMsg" + obj_id).innerHTML = ruleArr['errorMsg'];
					globalErrorMessage = globalErrorMessage + "\r\n"+ruleArr['errorMsg'];
				}
				else{
					document.getElementById("ErrMsg" + obj_id).innerHTML = "answer should be same";
					globalErrorMessage = globalErrorMessage + "\r\nanswer should be same";
				}
				document.getElementById("itemOnPage" + obj_id).style.display = "block";
				if(errorDisplayWay=='UseRedBoxErrorMessageInWebform')
				    document.getElementById("ErrMsg" + obj_id).style.display = "block";
			}
		}
		
		if(rule=='match'){
			obj_id = fieldAOrder;
			required = requireField(obj_id);
			if(required || !isEmpty(fieldA)){
				fieldB = ruleArr['extension'];
				try{
					var result = fieldA.match(fieldB);
				}catch(e){
					var result = false;
				}
				
				if(!result){
					isPass = false;
					$('#Field'+obj_id).addClass('errorBorder');
					console.log(ruleArr['errorMsg']);
					if(ruleArr['errorMsg']!=''&&ruleArr['errorMsg']!='undefined'&&ruleArr['errorMsg'].length > 0){
						document.getElementById("ErrMsg" + obj_id).innerHTML = ruleArr['errorMsg'];
						globalErrorMessage = globalErrorMessage + "\r\n"+ruleArr['errorMsg'];
					}
					else{
						document.getElementById("ErrMsg" + obj_id).innerHTML = "wrong format";
						globalErrorMessage = globalErrorMessage + "\r\nwrong format";
					}
					document.getElementById("itemOnPage" + obj_id).style.display = "block";
					if(errorDisplayWay=='UseRedBoxErrorMessageInWebform'){
						document.getElementById("ErrMsg" + obj_id).style.display = "block";
					}
				
				}
			}
		}
	}
	return isPass;
}

function getOrderById(fieldId){
	var idField = $('input[name^="HiddenFieldID"][value='+fieldId+']');
	if(idField.length>0){
		return idField.attr('name').substr(13);
	}
	else{
		return '';
	}
}

function findTypeLimit() {
	$("[id^=fieldtype]").each(function(j) {
		i=j+1;
		//console.log("fieldtype"+i);
		if ($('#fieldtype_' + i).val() == 'limit') 
		{
			fieldid=$("input[name='HiddenFieldID"+i+"']").val();
			fieldnum='Field'+i;
			reloadFieldLimit(fieldid,fieldnum);
		}
	});
}
function reloadFieldLimit(fieldid, fieldnum) {
	if (typeof globalTracker !== 'undefined') {
		tracker = globalTracker;
	}
	if (getParameterByName('tracker') != '') {
		tracker = getParameterByName('tracker');
	}
	// console.log(tracker);
	var times=Math.random();
	var url = hostname
			+ '/app/index.php/webforms/form/ajaxGetLimitQuotaByfieldid?id='
			+ fieldid + '&tracker=' + tracker+ '&times=' + times;
	$.ajax({
		type : 'GET',
		url : url,
		async : false,
		success : function(result) {
			$("#" + fieldnum).empty();
			$("#" + fieldnum).append(result);
		},
	});
}

function openFancyboxConfirm(){

	fancyconfirm("", {
	    buttons: [{
	        'class': "yes",
		        type: "button",
		        title: "確認",
		        value: "1"
	    	}, 
	    	{
		        'class': "no",
		        type: "button",
		        title: "取消",
		        value: "0"
	    	},
	    ],
	    modal: true
	},

	function (resp) {
		if(resp==1){
			var redeemCodeResult = redeemCode();
			if(redeemCodeResult==1){
				document.getElementById("mode").value = "Submit";
				replaceSalesforceData();
				var theForm = document.getElementById("formPreview");
				theForm.submit();
			}
			else{
				alert('error:'+redeemCodeResult);
			}
		} else if (resp==0) {
			$("#submitFormBtn").removeAttr('disabled');
			$("#submitFormBtn").removeClass('disabledbtn');
		}
	});
	setTimeout('$("#submitFormBtn").attr("disabled","disabled");',100);
}

function openFancyboxConfirmNoRedemption(formtype){

	fancyconfirm("", {
	    buttons: [{
	        'class': "yes",
		        type: "button",
		        title: "確認",
		        value: "1"
	    	}, 
	    	{
		        'class': "no",
		        type: "button",
		        title: "取消",
		        value: "0"
	    	},
	    ],
	    modal: true
	},

	function (resp) {
		if(resp==1){
			switch (formtype)  {
				case "Redemption Form":
					var redeemCodeResult = redeemCode();
					if(redeemCodeResult==1){
						document.getElementById("mode").value = "Submit";
						replaceSalesforceData();
						var theForm = document.getElementById("formPreview");
						theForm.submit();
					}
					else{
						alert('error:'+redeemCodeResult);
					}
					break;
				default:
					document.getElementById("mode").value = "Submit";
				    replaceSalesforceData();
					var theForm = document.getElementById("formPreview");
					theForm.submit();
			}
			
		}
	});
	setTimeout('$("#submitFormBtn").attr("disabled","disabled");',100);
}